import React, { PureComponent } from "react";
import { Form, Input, Button } from "antd";
import { connect } from "react-redux";
import { push, goBack } from "react-router-redux";
import backMailbox from "../../assets/images/backMailbox.png";
import { GetMobileCode, api_mobile_onetep } from "../../services/api/user";
import style from "./style.less";
import { errCode } from "../../helper/errCode";
import ErrTip from "../ErrTip";
const FormItem = Form.Item;

class ForgetMobile extends PureComponent {
  state = {
    tipFont: "获取验证码",
    disableCode: true,
    index: 60,
    timeStamp: ""
  };

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (err) return;
      api_mobile_onetep({
        ...values,
        sms_type: 1,
        return_type: "json"
      }).then(data => {
        const response = data.data;
        const flag = String(response.flag);
        if (flag !== "0") {
          console.log(flag, errCode[flag]);
          this.props.form.setFields({
            code: {
              value: values.code,
              errors: [new Error(errCode[flag])]
            }
          });
        } else {
          this.props.nextStep(values.mobile, values.code);
        }
      });
    });
  };

  getCode = () => {
    this.props.form.validateFields(["mobile", "captcha"], (err, value) => {
      if (err) return;

      if (this.state.disableCode) {
        GetMobileCode({
          ...value,
          sms_type: 1,
          appid: 1,
          return_type: "json",
          country: "+86"
        }).then(data => {
          const response = data.data;
          const flag = String(response.flag);
          if (flag !== "0") {
            console.log(flag, errCode[flag]);
            this.changeImgCode();
            this.props.form.setFields({
              captcha: {
                value: "",
                errors: [new Error(errCode[flag])]
              }
            });
          } else {
            this.timer = setInterval(() => {
              if (this.state.index <= 0) {
                return this.Clear();
              }
              this.setState({
                disableCode: false,
                index: this.state.index - 1,
                tipFont: `已发送(${this.state.index - 1}s)`
              });
            }, 999);
          }
        });
      }
    });
  };

  changeImgCode = () => {
    let date = new Date();
    let timeStamp = date.getTime();
    this.setState({ timeStamp });
  };

  Clear = () => {
    this.setState({
      disableCode: true,
      index: 60,
      tipFont: "获取验证码"
    });
    clearInterval(this.timer);
  };

  render() {
    const { tipFont, disableCode, timeStamp } = this.state;
    const { getFieldDecorator } = this.props.form;

    return (
      <div className={style.Mobilepassword}>
        <Form className={style.mobile_form} onSubmit={this.handleSubmit}>
          <FormItem>
            <div className={style.formItem}>
              {getFieldDecorator("mobile", {
                rules: [
                  {
                    pattern: /^1[3456789]\d{9}$/,
                    message: <ErrTip>请输入正确的手机号</ErrTip>
                  },
                  {
                    required: true,
                    message: <ErrTip>请输入注册时使用的手机号</ErrTip>
                  }
                ],
                initialValue: ""
              })(
                <Input
                  addonBefore={""}
                  style={{ width: "100%" }}
                  placeholder="请输入常用手机号"
                  onFocus={this.clearErr}
                />
              )}
            </div>
          </FormItem>
          <FormItem>
            <div className={style.formItem}>
              <div className={style.codeWrap}>
                {getFieldDecorator("captcha", {
                  rules: [
                    {
                      required: true,
                      message: <ErrTip>请输入图形验证码</ErrTip>
                    }
                  ]
                })(
                  <Input
                    className={`${style.formInput} ${style.code}`}
                    placeholder="请输入图形验证码"
                  />
                )}
                <div className={style.imgCode}>
                  <img src={`/u/captcha?t=${timeStamp}`} alt="图形验证码" />
                </div>
              </div>
            </div>
          </FormItem>
          <FormItem>
            <div className={style.formItem}>
              <div className={style.msgWrap}>
                {getFieldDecorator("code", {
                  rules: [
                    {
                      required: true,
                      message: <ErrTip>请输入短信验证码</ErrTip>
                    }
                  ]
                })(
                  <Input
                    className={`${style.formInput} ${style.msg}`}
                    placeholder="请输入短信验证码"
                  />
                )}
                <div
                  className={`${style.getMsg} ${
                    disableCode ? null : style.disabledCode
                  }`}
                  onClick={this.getCode}
                >
                  {tipFont}
                </div>
              </div>
            </div>
          </FormItem>
          <FormItem>
            <Button
              type="primary"
              htmlType="submit"
              className={style.mobile_form_button}
            >
              下一步
            </Button>
          </FormItem>
        </Form>
        <div className={style.Moreoperations}>
          <a
            onClick={() => this.props.navigateTo("/login")}
            className={style.backLogin}
          >
            返回登录
          </a>
          <span className={style.vertical}>|</span>

          <a
            onClick={() => this.props.navigateTo("/emailPassword")}
            className={style.backLogin}
          >
            通过邮箱找回
            <img src={backMailbox} alt="" className={style.backMailbox} />
          </a>
        </div>
      </div>
    );
  }
}
const mapStateToProps = (state, ownProps) => {
  return {};
};

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    navigateTo: location => {
      dispatch(push(location));
    },
    goBack: () => {
      dispatch(goBack());
    }
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Form.create({})(ForgetMobile));
